/* -----------------
* brief
* 1. this is code gen by tools
* 2. mvc code are driver by the model defined with the same filename,
	 for example:
	 there is a Xmodel struct define in xmodel.go file, after the script run (lego model-mvc module_name xmodel)
     it will auto create the code under the module's path
	 m --> xmodel.go
	 v --> view
	 c --> xmodel_ctrl
* 3. you should modify this code if it doesn't satisfy your purpose
*/

package controller

import (
	"fmt"
	"saas_sys_base/common/url_const"

	"github.com/mjiulee/lego"
	_ "github.com/mjiulee/lego"
	_ "github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"
	"log"
	//. "lego_wechat/modules/wechat/models"
	//. "lego_wechat/modules/wechat/service"

	_ "encoding/json"

	mchcore "github.com/chanxuehong/wechat/mch/core"

	"github.com/chanxuehong/wechat/mp/core"
	"github.com/chanxuehong/wechat/mp/menu"
	"github.com/chanxuehong/wechat/mp/message/callback/request"
	"github.com/chanxuehong/wechat/mp/message/callback/response"
	_ "github.com/chanxuehong/wechat/mp/oauth2"
	configService "saas_sys_base/modules/config/service"
)

type WechatSdkCallbackCtrl struct {
	//service  WechatSdkService
	appConfigService configService.AppConfigService
}

func init() {
	vc := new(WechatSdkCallbackCtrl)
	_ctrlList = append(_ctrlList, vc)
}

func (vc *WechatSdkCallbackCtrl) CtrlInfo() string {
	return "WechatSdkCtrl"
}

func (vc *WechatSdkCallbackCtrl) RoutInit() {
	lego.APIGETWITHOUTSIGN("/wx_callback", wxCallbackHandlerEx)
	lego.APIPOSTWITHOUTSIGN("/wx_callback", wxCallbackHandlerEx)

	//lego.APIGETWITHOUTSIGN("/wx_callback", wxCallbackHandlerEx)
	//"/wx_pay_callback/*subpath"
	lego.APIPOSTWITHOUTSIGN(url_const.WX_PAY_CALLBACK_URL + "/*" + url_const.SUBPATH_LABEL, WxMchPayCallbackHandlerEx)
	lego.APIPOSTWITHOUTSIGN(url_const.WX_MCHv3_CALLBACK_URL + "/:" + url_const.SUBPATH_MCHID + "/:" + url_const.SUBPATH_APPID, WxMchv3CallbackHandlerEx)
}

/*
var (
	// 下面两个变量不一定非要作为全局变量, 根据自己的场景来选择.
	msgHandler core.Handler
	msgServer  *core.Server
)
*/

/*func defaultEventHandler(ctx *fasthttp.RequestCtx) {
	log.Printf("收到事件:\n%s\n", ctx.MsgPlaintext)
	ctx.NoneResponse()
}*/
/*
func init() {
	http.HandleFunc("/wx_callback", wxCallbackHandler)
}
*/
// wxCallbackHandler 是处理回调请求的 http handler.
//  1. 不同的 web 框架有不同的实现
//  2. 一般一个 handler 处理一个公众号的回调请求(当然也可以处理多个, 这里我只处理一个)
/*func wxCallbackHandler(w http.ResponseWriter, r *http.Request) {
	msgServer.ServeHTTP(w, r, nil)
}*/

func wxCallbackHandlerEx(ctx *fasthttp.RequestCtx) {
	//注意：这个handle函数要注册GET和POST方法
	var args *fasthttp.Args
	args = ctx.QueryArgs()

	appid := string(args.Peek("appid"))
	msgServer := GetMpServerByWeappId(appid)
	if msgServer == nil {
		ctxExt := lego.RequestCtxExtent{ctx}
		response := make(map[string]interface{})
		response["code"] = 0
		response["msg"] = fmt.Sprintf("can not find the appid %s", appid)
		ctxExt.JSON(500, response)
		return
	}
	msgServer.ServeHTTP(ctx) //这是产的接口，我把他从“w http.ResponseWriter, r *http.Request”变为“ctx *fasthttp.RequestCtx”

}

func StartWxServer() {

}

func textMsgHandler(ctx *core.Context) {
	log.Printf("收到文本消息:\n%s\n", ctx.MsgPlaintext)

	msg := request.GetText(ctx.MixedMsg)

	resp := response.NewText(msg.FromUserName, msg.ToUserName, msg.CreateTime, msg.Content)
	ctx.RawResponse(resp) // 明文回复
	//ctx.AESResponse(resp, 0, "", nil) // aes密文回复
}

func defaultMsgHandler(ctx *core.Context) {
	log.Printf("收到消息:\n%s\n", ctx.MsgPlaintext)
	ctx.NoneResponse()
}

func menuClickEventHandler(ctx *core.Context) {
	log.Printf("收到菜单 click 事件:\n%s\n", ctx.MsgPlaintext)

	event := menu.GetClickEvent(ctx.MixedMsg)
	resp := response.NewText(event.FromUserName, event.ToUserName, event.CreateTime, "收到 click 类型的事件")
	//ctx.RawResponse(resp) // 明文回复
	ctx.AESResponse(resp, 0, "", nil) // aes密文回复
}

func defaultEventHandler(ctx *core.Context) {
	log.Printf("收到事件:\n%s\n", ctx.MsgPlaintext)

	ctx.NoneResponse()
}

//mch callback

func WxMchPayCallbackHandlerEx(ctx *fasthttp.RequestCtx) {
	//ctxExt := &lego.RequestCtxExtent{ctx}
	var appid string
	var mchid string

	msg, err := mchcore.DecodePayNotifyCallback(ctx)
	if err != nil {
		mchcore.DefaultErrorHandler.ServeError(ctx, err)
		return
	}

	appid = msg["appid"]
	mchid = msg["mch_id"]
	//
	msgServer := GetMchServerByAppidAndMchId(appid, mchid)
	if msgServer == nil {
		mchcore.DefaultErrorHandler.ServeError(ctx, fmt.Errorf("mchid<%s> appid<%s> not register in the system", mchid, appid))
		return
	}
	msgServer.ServeHTTP(ctx) //这是产的接口，我把他从“w http.ResponseWriter, r *http.Request”变为“ctx *fasthttp.RequestCtx”
}
